package com.cxy.service.impl;

import com.cxy.mapper.EmpMapper;
import com.cxy.pojo.Emp;
import com.cxy.pojo.PageBean;
import com.cxy.service.EmpService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    /**
     * 分页查询执行函数
     * @param pageSize ：每页需要的记录数目
     * @param pageOffset: 根据前端传递的页码计算的页码偏移
     *                  pageOffset = (page -1)*pageSize
     * @return
     */
    public PageBean limitSelect(Integer pageSize, Integer pageOffset){
        Long countNum = empMapper.countNum();
        List<Emp> empList = empMapper.listSelect(pageSize, pageOffset);
        PageBean pageBean = new PageBean(countNum,empList);
        return pageBean;
    }

    /**
     * 使用PageHelper的分页查询
     * @param pageSize
     * @param page
     * @return
     */
    @Override
    public PageBean limitPageHelperSelect(Integer pageSize, Integer page) {
        PageHelper.startPage(page,pageSize);
        List<Emp> list = empMapper.list();
        Page<Emp> p = (Page<Emp>) list;

        PageBean pageBean = new PageBean(p.getTotal(),p.getResult());

        return pageBean;
    }

    /**
     * 使用PageHelper的条件分页查询
     * @param pageSize
     * @param page
     * @param name
     * @param gender
     * @param begin
     * @param end
     * @return
     */
    @Override
    public PageBean limitIfSelect(Integer pageSize, Integer page, String name, Short gender, LocalDate begin, LocalDate end) {
        PageHelper.startPage(page,pageSize);
        List<Emp> list = empMapper.ifList(name,gender,begin,end);
        Page<Emp> p = (Page<Emp>) list;

        PageBean pageBean = new PageBean(p.getTotal(),p.getResult());
        return pageBean;
    }

    @Override
    public void delete(List<Integer> ids) {
        empMapper.deletebyIds(ids);
    }

    @Override
    public void insert(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.insert(emp);
    }

    @Override
    public Emp getById(Integer id) {
        Emp emp = empMapper.getById(id);
        return emp;
    }

    @Override
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateEmp(emp);
    }

    /**
     * 用户登入功能
     * @param emp
     * @return
     */
    @Override
    public Emp login(Emp emp) {
        return empMapper.getByUsernameAndPassword(emp);
    }
}
